/* eslint react/prefer-stateless-function:0, react/prop-types:0 */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { hashHistory } from 'react-router';
import { Icon, message } from 'antd';
import style from './style.css';
import * as actions from '../../../actions/openAudio';
import qrcode from '../../../images/qrcode.jpg';

@connect(
  (state, props) => ({
    openAudio: state.openAudio,
  }), actions
)
export default class extends Component {

  componentWillMount() {
    this.updatePlay(this.props.location);
  }

  componentDidMount() {
    const audio = document.getElementById('audio');
    const { update } = this.props;

    wx.config({});

    wx.ready(() => {
      audio.play();
      update({
        playing: true,
      });
    });

    document.addEventListener("WeixinJSBridgeReady", function () {
      audio.play();
      update({
        playing: true,
      });
    }, false);

    audio.addEventListener('canplaythrough', () => {
      audio.play();
      update({
        playing: true,
      });
    });

    audio.addEventListener('timeupdate', () => {
      const currentTime = Math.round(audio.currentTime * 100);
      const duration = Math.round(audio.duration * 100);
      update({
        progress: `${(currentTime / duration).toFixed(2) * 100}%`,
      });
    }, false);

    audio.addEventListener('ended', () => {
      const { times, playList } = this.props.openAudio;
      update({
        playing: false,
        progress: '0%',
      });

      // 如果存在下一首
      const nextId = Object.keys(playList)[0];
      if (nextId) {
        message.info('即将播放下一首', 0.8);
      }

      setTimeout(() => {
        if (times <= 1) {
          if (nextId) {
            hashHistory.replace(`/open/audio/detail?id=${nextId}`);
          }
        } else {
          update({
            playing: true,
            times: times - 1,
          });
          audio.play();
        }
      }, 1000);
    }, false);

    hashHistory.listen((listenner) => {
      this.updatePlay(listenner);
      setTimeout(() => {
        this.play();
      }, 0);
    });
  }

  updatePlay({ query }) {
    const { update, openAudio } = this.props;
    const { id } = query;
    const { playList, type } = openAudio;
    const audioType = `audio${type}`;
    const audioList = openAudio[audioType] || [];
    const newPlayList = { ...playList };
    if (!id) {
      return;
    }

    if (+playList[id] > 1) {
      update({
        times: +playList[id],
      });
    }
    delete newPlayList[id];
    update({
      current: audioList.filter(item => +item.id === +id)[0],
      playList: newPlayList,
    });
  }

  play() {
    const { update } = this.props;
    const audio = document.getElementById('audio');
    if (!audio) {
      return false;
    }
    if (audio.paused) {
      audio.play();
      update({
        playing: true,
      });
    } else {
      audio.pause();
      update({
        playing: false,
      });
    }
  }

  render() {
    const { playing, progress, audio, current } = this.props.openAudio;

    return (
      <div className={style.container}>
        <div className={style.panel}>
          <div className={style.bg}>
            <img src="http://7xlmr2.com1.z0.glb.clouddn.com/bg.jpg" />
          </div>
          <div className={style.banner}>
            <div className={style.logo}></div>
            <div className={style.controls}>
              {
                playing
                  ? <Icon type="pause" className={style.play_btn} onClick={::this.play} />
                  : <Icon type="caret-right" className={style.play_btn} onClick={::this.play} />
              }
              <div className={style.progress}>
                <div className={style.real_progress} style={{ width: progress }}></div>
              </div>
              <audio preload="auto" id="audio" src={current.src}>
                对不起，您的设备不支持播放语音。
              </audio>
            </div>
          </div>
        </div>
        <div className={style.name}>
          <div className={style.glass}>
          </div>
          {current.name || '' }
          </div>
        <div className={style.words}>
          <div className={style.glass}>
          </div>
          {
            current.lyrics && current.lyrics.split(/\n/g).map((text, index) =>
              /[\u4e00-\u9fa5]+/img.test(text)
                ?
                <div key={index}>{text}</div>
                :
                <div key={index} className={style.blue}>{text}</div>
            )
          }
        </div>
        <div className={style.qr_code}>
          <img src={qrcode} width="100%" />
        </div>
      </div>
    );
  }
}